package com.lydms.interval;

import com.lydms.service.WordSmsService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@EnableScheduling
public class SmsIterval {

    private final static Logger logger = LogManager.getLogger(SmsIterval.class);

//    定时时间1
    @Value(value = "${send1}")
    private boolean send1;
//    定时时间2
    @Value(value = "${send2}")
    private boolean send2;
//    定时时间3
    @Value(value = "${send3}")
    private boolean send3;
//  手机号
    @Value(value = "${sendSms.phone}")
    private String phone;

    @Autowired
    private WordSmsService wordSmsService;


    /**
     * 定时时间1，发送短信
     */
    @Scheduled(cron = "${interval.sendSms1}")
    public void intervalSms1() {
        timeLog();
        if (send1) {
            sendSms(phone);
        }else {
            logger.info("此时间点不发送短信");
        }
    }


    /**
     * 定时时间2，发送短信
     */
    @Scheduled(cron = "${interval.sendSms2}")
    public void intervalSms2() {
        timeLog();
        if (send2) {
            sendSms(phone);
        }
        logger.info("此时间点不发送短信");
    }


    /**
     * 定时时间3，发送短信
     */
    @Scheduled(cron = "${interval.sendSms3}")
    public void intervalSms3() {
        timeLog();
        if (send3) {
            sendSms(phone);
        }else {
            logger.info("此时间点不发送短信");
        }
    }

    /**
     * 发送短信
     * @param iphone    手机号
     */
    private void sendSms(String iphone) {
        String result = wordSmsService.sendSms(iphone, 1234);
        if (result == null) {
            logger.info("给:{}发送短信失败", iphone);
        }else {
            logger.info("给:{}发送短信成功", iphone);
        }
    }

    /**
     * 打印当前时间
     */
    private void timeLog() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String format1 = format.format(date);
        logger.info(format1 + " 发送定时短信，手机号为:{}", phone);
    }
}
